package com.xgure.interceptor;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.xgure.constant.JwtConstant;
import com.xgure.properties.JwtProperties;
import com.xgure.utils.JwtUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

// 管理端登录拦截器
@Component
public class JwtAdminInterceptor implements HandlerInterceptor {

    private static final Logger log = LoggerFactory.getLogger(JwtAdminInterceptor.class);
    @Resource
    private JwtProperties jwtProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("拦截到请求：{}", request.getRequestURI());

        // 验证获取的token是否合法
        try {
            String header = request.getHeader(jwtProperties.getHeader());
            DecodedJWT decodedJWT = JwtUtil.verifyToken(header, jwtProperties.getSecret());
            Long id = Long.valueOf(decodedJWT.getClaim(JwtConstant.CLAIM).asString());

            return true;
        } catch (Exception ex) {
            log.error("拦截器验证token失败：{}", ex.getMessage());
            response.setStatus(401);
            return false;
        }
    }
}
